package com.fancy.learncenter.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonContructSatisticsesBean;
import com.fancy.learncenter.bean.CartoonCountDoneWorkBean;
import com.fancy.learncenter.bean.CartoonFinishWorkBean;
import com.fancy.learncenter.bean.CartoonQuestionBankBean;
import com.fancy.learncenter.bean.CartoonStudentStatisBean;
import com.fancy.learncenter.bean.QuestionVOsBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.common.LoginUserSharePrefernce;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.adapter.CartoonStaticsAdapter;
import com.fancy.learncenter.ui.callback.AlbumImpl;
import com.fancy.learncenter.utils.FileUtils;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.Utils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class CartoonStaticsActivity extends BaseActivity {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.previous_question)
    ImageView previousQuestion;
    @Bind(R.id.commit_image)
    ImageView commitImage;
    @Bind(R.id.next_question)
    ImageView nextQuestion;
    @Bind(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    @Bind(R.id.teching_material_name)
    TextView techingMaterialName;
    @Bind(R.id.unit_name)
    TextView unitName;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    ArrayList<QuestionVOsBean> questionArrayList = new ArrayList<>();
    JumpIntentKey.QUESTION_ENTER_TYPE type;
    @Bind(R.id.do_work_end_time)
    TextView doWorkEndTime;
    @Bind(R.id.work_report_end_time)
    TextView workReportEndTime;
    @Bind(R.id.accuracy_text)
    TextView accuracyText;
    @Bind(R.id.work_report_accuracy_layout)
    RelativeLayout workReportAccuracyLayout;
    private String unitNameStr;
    private String lessonNameStr;
    CartoonStaticsAdapter adapter;
    private List<CartoonContructSatisticsesBean> staticsList = new ArrayList<>();
    private String homePackageId;
    private String studentHomeworkId;
    private int completeNum;
    private CartoonFinishWorkBean finishWorkBean;
    private String totalQuestionNum;
    Gson gson = new Gson();

    String releaseTime = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCartoonContentView(R.layout.activity_cartoon_statics, Status.STATUS);
        ButterKnife.bind(this);
        getIntentData();
        initView();
        initRecycleView();
    }

    private void getIntentData() {
        type = (JumpIntentKey.QUESTION_ENTER_TYPE) getIntent().getSerializableExtra(JumpIntentKey.QUESTION_ENTER);
        unitNameStr = getIntent().getStringExtra(JumpIntentKey.UNIT_NAME);
        lessonNameStr = getIntent().getStringExtra(JumpIntentKey.LESSON_NAME);
        homePackageId = getIntent().getStringExtra(JumpIntentKey.HOMEWORK_PACKAGE_ID);
        studentHomeworkId = getIntent().getStringExtra(JumpIntentKey.STUDENTHOMEWORKID);
        releaseTime = getIntent().getStringExtra("releaseTime");
        techingMaterialName.setText(lessonNameStr);
        totalQuestionNum = getIntent().getStringExtra(JumpIntentKey.QUESTION_NUM);
        unitName.setText(unitNameStr);
    }

    private void initView() {
        previousQuestion.setVisibility(View.GONE);
        nextQuestion.setVisibility(View.GONE);
        switch (type) {
            case DO_WORK:
            case CONTINUE_WORK:
                doWorkEndTime.setVisibility(View.VISIBLE);
                workReportAccuracyLayout.setVisibility(View.GONE);
                initData();
                getStaticsData();
                break;

            case FINISH_WORK:
                doWorkEndTime.setVisibility(View.VISIBLE);
                workReportAccuracyLayout.setVisibility(View.GONE);
                getStaticsData();
                commitImage.setImageResource(R.mipmap.cartoon_finish_work);
                break;

            case WORK_REPORT:
                workReportAccuracyLayout.setVisibility(View.VISIBLE);
                doWorkEndTime.setVisibility(View.GONE);
                initData();
                bottomLayout.setVisibility(View.GONE);
                getStaticsReport();
                break;

        }

        commitImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.MyLog("completeNum", "=====completeNum==" + completeNum);
                switch (type) {
                    case DO_WORK:
                        setRecordTime();
                        Intent intent = new Intent(getBaseContext(), CartoonWorkQuestionTypeActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(JumpIntentKey.QUESTION_ENTER, JumpIntentKey.QUESTION_ENTER_TYPE.DO_WORK);
                        bundle.putParcelableArrayList(JumpIntentKey.QUSETION_BANK_LIST_KEY, questionArrayList);
                        bundle.putString(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
                        bundle.putString(JumpIntentKey.STUDENTHOMEWORKID, studentHomeworkId);
                        bundle.putString(JumpIntentKey.LESSON_NAME, lessonNameStr);
                        bundle.putInt(JumpIntentKey.CURRENT_INDEX, completeNum);
                        bundle.putString(JumpIntentKey.UNIT_NAME, unitNameStr);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        finish();


                        break;
                    case CONTINUE_WORK: //继续做作业
                        setRecordTime();
                        Intent intent1 = new Intent(getBaseContext(), CartoonWorkQuestionTypeActivity.class);
                        Bundle bundle1 = new Bundle();
                        bundle1.putSerializable(JumpIntentKey.QUESTION_ENTER, JumpIntentKey.QUESTION_ENTER_TYPE.CONTINUE_WORK);
                        bundle1.putParcelableArrayList(JumpIntentKey.QUSETION_BANK_LIST_KEY, questionArrayList);
                        bundle1.putString(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
                        bundle1.putString(JumpIntentKey.STUDENTHOMEWORKID, studentHomeworkId);
                        bundle1.putInt(JumpIntentKey.CURRENT_INDEX, completeNum);
                        bundle1.putString(JumpIntentKey.LESSON_NAME, lessonNameStr);
                        bundle1.putString(JumpIntentKey.UNIT_NAME, unitNameStr);
                        intent1.putExtras(bundle1);
                        startActivity(intent1);
                        finish();
                        break;

                    case FINISH_WORK:
//                      getRecordTime();
                        Bundle bundle2 = new Bundle();
                        bundle2.putSerializable(JumpIntentKey.QUESTION_ENTER, type);
                        bundle2.putLong(JumpIntentKey.ANSWER_QUESTION_DURATION, getRecordTime());
                        bundle2.putString(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
                        bundle2.putString(JumpIntentKey.STUDENTHOMEWORKID, studentHomeworkId);
                        Intent intentFinish = new Intent(getBaseContext(), CartoonFinishedActivity.class);
                        intentFinish.putExtras(bundle2);
                        startActivity(intentFinish);
                        finish();
                        break;
                }
            }
        });
    }

    /**
     * 设置起始时间
     */
    private void setRecordTime() {
        long time = System.currentTimeMillis();
        Log.i("startTime----", time + "");
        LoginUserSharePrefernce.setRecordStartTime(time, homePackageId);
    }


    /**
     * 获取提包答题时长
     */
    private long getRecordTime() {

        long startTime = LoginUserSharePrefernce.getRecordStartTime(String.valueOf(homePackageId));
//        long startTime = 0;
//
//        if (!TextUtils.isEmpty(startTimeStr)) {
//            startTime = Long.valueOf(startTimeStr);
//        }
        Log.i("startTime----", startTime + "");
        long endTime = System.currentTimeMillis();
        Log.i("endTime----", endTime + "");
        long timeDuration = endTime - startTime;
        Log.i("timeDuration----", timeDuration + "");
        long beforeTimeDuration = LoginUserSharePrefernce.getCartoonQuestionTime(homePackageId);

//        long beforeTimeDuration = 0;
//        if (!TextUtils.isEmpty(beforeTimeDurationStr)) {
//            beforeTimeDuration = Long.valueOf(beforeTimeDurationStr);
//        }
        long duration = timeDuration + beforeTimeDuration;
        Log.i("duration----", duration + "");
        LoginUserSharePrefernce.setCartoonQuestionTime(duration, homePackageId);
        LoginUserSharePrefernce.setRecordStartTime(0, homePackageId);
        Log.i("duration----", duration + "");
        return duration;
    }


    /**
     * 获取首次完成作业的数量
     */
    private void getCountWork() {

        Map<String, Object> map = new HashMap<>();
        map.put("classId", MyApplication.classIDStr);
        map.put("homeworkPackageId", homePackageId);
        map.put("studentHomeworkId", studentHomeworkId);
        HttpMehtod.getInstance().cartoonCountHomeWorks(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonCountDoneWorkBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonCountDoneWorkBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonCountDoneWorkBean>() {
                    @Override
                    public void success(CartoonCountDoneWorkBean dataBean) {


                        long questionId = dataBean.getResult();

                        for (int i = 0; i < questionArrayList.size(); i++) {

                            LogUtil.MyLog("completeNum", questionId + "=====questionId==" + questionArrayList.get(i).getQuestionId() + "------" + i);

                            if (questionId == questionArrayList.get(i).getQuestionId()) {
                                completeNum = i;
                            }
                        }
                        LogUtil.MyLog("completeNum", "=====completeNum==" + completeNum);
                        if (completeNum == 0) {
                            type = JumpIntentKey.QUESTION_ENTER_TYPE.DO_WORK;
                            commitImage.setImageResource(R.mipmap.cartoon_start_work);
                        } else {
                            type = JumpIntentKey.QUESTION_ENTER_TYPE.CONTINUE_WORK;
                            commitImage.setImageResource(R.mipmap.cartoon_continue_work);
                        }

                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }


    /**
     * 获取作业报告-统计数据
     */
    private void getStaticsReport() {

        Map<String, Object> map = new HashMap<>();
        map.put("studentHomeworkId", studentHomeworkId);

        HttpMehtod.getInstance().cartoonStaticsReport(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonStudentStatisBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonStudentStatisBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonStudentStatisBean>() {
                    @Override
                    public void success(CartoonStudentStatisBean dataBean) {

                        if (dataBean != null) {
                            if (!TextUtils.isEmpty(dataBean.getStudentHomeworktSatistics().getAccuracy())) {
                                accuracyText.setText(dataBean.getStudentHomeworktSatistics().getAccuracy());
                            }
                            if (!TextUtils.isEmpty(dataBean.getStudentHomeworktSatistics().getEndTime())) {
                                workReportEndTime.setText(dataBean.getStudentHomeworktSatistics().getEndTime());
                            }

                            staticsList.addAll(dataBean.getStudentHomeworktSatistics().getHomeworkContructSatisticses());

                            adapter.notifyDataSetChanged();

                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();

            }
        });

    }


    /**
     * 做作业--进度
     */
    private void getStaticsData() {

        Map<String, Object> map = new HashMap<>();
        map.put("studentHomeworkId", studentHomeworkId);
        HttpMehtod.getInstance().cartoonStaticsWork(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonStudentStatisBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonStudentStatisBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonStudentStatisBean>() {
                    @Override
                    public void success(CartoonStudentStatisBean dataBean) {

                        if (dataBean != null) {
                            if (!TextUtils.isEmpty(dataBean.getStudentHomeworktSatistics().getEndTime())) {
                                doWorkEndTime.setText(dataBean.getStudentHomeworktSatistics().getEndTime());
                            }

                            staticsList.addAll(dataBean.getStudentHomeworktSatistics().getHomeworkContructSatisticses());
                            adapter.notifyDataSetChanged();

                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();

            }
        });
    }

    private void initRecycleView() {

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new CartoonStaticsAdapter(this, type, staticsList);
        recyclerView.setAdapter(adapter);

        adapter.setListener(new AlbumImpl() {
            @Override
            public void onClick(int position) {
                CartoonContructSatisticsesBean item = staticsList.get(position);
                ArrayList<String> tempList = new ArrayList<>();

                for (int i = 0; i < item.getQuestionIds().size(); i++) {
                    tempList.add(String.valueOf(item.getQuestionIds().get(i)));
                }

                ArrayList<QuestionVOsBean> questionList = new ArrayList<>();
                for (int i = 0; i < questionArrayList.size(); i++) {
                    for (int j = 0; j < tempList.size(); j++) {
                        if (String.valueOf(questionArrayList.get(i).getQuestionId()).equals(tempList.get(j))) {
                            QuestionVOsBean bean = questionArrayList.get(i);
                            questionList.add(bean);
                        }
                    }
                }

//                Intent intent = new Intent(getBaseContext(), CartoonQuestionTypeActivity.class);
                Intent intent = new Intent(getBaseContext(), CartoonWorkQuestionTypeActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(JumpIntentKey.QUESTION_ENTER, JumpIntentKey.QUESTION_ENTER_TYPE.WORK_REPORT);
                bundle.putParcelableArrayList(JumpIntentKey.QUSETION_BANK_LIST_KEY, questionList);
                bundle.putString(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
                bundle.putString(JumpIntentKey.STUDENTHOMEWORKID, studentHomeworkId);

                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }

    private void initData() {
        String fileName = Constant.CARTOON_QUESTION_BANK + String.valueOf(LoginUserSharePrefernce.getCustomId() + "_" + homePackageId) + ".td";
        downloadWork(fileName, studentHomeworkId);
//        if (!FileUtils.checKFileExists(Constant.CARTOON_QUESTION_BANK + fileName)) {
//            downloadWork(fileName, studentHomeworkId);
//        } else {
//            String readResultStr = FileUtils.readFromSD(fileName);
//            CartoonQuestionBankBean questionBankBean1 = gson.fromJson(readResultStr, CartoonQuestionBankBean.class);
//            questionArrayList.addAll(questionBankBean1.getQuestionVOs());
//        }
    }

    /**
     * 下载作业包
     *
     * @param fileName
     * @param homeworkId
     */
    private void downloadWork(final String fileName, String homeworkId) {


        Map<String, Object> map = new HashMap<>();
        map.put("studentHomeworkId", String.valueOf(homeworkId));
        HttpMehtod.getInstance().cartoonDownloadHomeWorkById(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonQuestionBankBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonQuestionBankBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonQuestionBankBean>() {
                    @Override
                    public void success(CartoonQuestionBankBean dataBean) {
                        dataBean.setReleaseTime(releaseTime);

                        String str = gson.toJson(dataBean);

                        FileUtils.creatFile(fileName);
                        FileUtils.saveStringToFile(fileName, str);
                        String readResultStr = FileUtils.readFromSD(fileName);
                        CartoonQuestionBankBean questionBankBean1 = gson.fromJson(readResultStr, CartoonQuestionBankBean.class);
                        questionArrayList.addAll(questionBankBean1.getQuestionVOs());

                        getCountWork();
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }


}

